﻿using RM_dll2.Process;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using FinalTestMachine.Connect;
using FinalTestMachine.Motion.Aixs;
using FinalTestMachine.Motion.IO;
using FinalTestMachine.Motion.Product;
using FinalTestMachine.Motion.Products;
using FinalTestMachine.View.MainUnits;
using RM_dll2.IoCylinder;
using AviewMotionUI.MachineLife;
using AviewMotionUI.ProductionStatistics;
using FinalTestMachine.Motion.Process.RunModel;
using AM.Tools;
using FinalTestMachine.MES;
using FinalTestMachine.Core.FileOperate;
using FinalTestMachine.View;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using FinalTestMachine.Funs;
using RM_dll2;
using System.Windows.Forms;
using FinalTestMachine.Motion.Process.SubProcess;
using WpfZMotion_AAControl.Core.Tools;

namespace FinalTestMachine.Motion.Process
{
    internal class Process_AutoRun : RM_dll2.Process.ProcessAutoRunBase
    {
        public static readonly Process_AutoRun Cur = new Process_AutoRun();

        public bool CurrentSocketCanUse => Funs.FunSocketSettings.Cur.CheckSocketCanUse(RotatedMovNextHelper.tagPos[0]);

        private Process_AutoRun() : base("自动运行", StaticInitial.Motion, true)
        {
            Connect.ConnectFactory.TCP_ScanCode.RecevieMsgActionEventHander += SerialPort_ScanCode_RecevieMsgActionEventHander;
        }

        private void SerialPort_ScanCode_RecevieMsgActionEventHander(string obj)
        {
            obj = obj.Trim();
            if (string.IsNullOrEmpty(obj) || obj.ToLower() == "noread" || obj.ToLower() == "error")
            {
                //WriteToUser($"扫码内容有错不应为:{obj}",Brushes.Red,true);
                return;
            }

            SN = string.Empty;

            if (FunCommSelection.Cur.EnableBuzzarTipsAfterScanSucess)
            {
                StaticIOHelper.BuzzarReminder();
            }
            else
            {
                StaticIOHelper.DualLightTwinkle();
            }
            
            SN = obj;
           
            WriteToUser($"获取到SN:{SN}", Brushes.Green, true);

            if (FunCommSelection.Cur.EnablePrefixCheck)
            {
                if (!SN.Contains(OtherParamHelper.Cur.SnPrefix.GetValue))
                {
                    StaticIOHelper.BuzzarReminder();
                    WriteErrToUser($"当前SN不包含指定区别码:{OtherParamHelper.Cur.SnPrefix.GetValue}");
                    SN = "";
                    return;
                }
            }

            if (Funs.FunCommSelection.Cur.IsUseMes && !FunCommSelection.Cur.IsUseSpotCheck)
            {
                ReTryCheckSN(SN);
            }
        }

        private void ReTryCheckSN(string ProductSN)
        {
            if (MESHelper.Cur.CheckSN(ProductSN, out string error) == false)
            {
                Task<string> result = null;

                App.Current.Dispatcher.Invoke(() =>
                {
                    var content = $"CheckSN失败：{error}！是否重试？";
                    StaticInitial.Motion.WriteErrToUser(content);
                    result = new View.WarningView(content, "重试", "作为NG品").ShowDialog();
                });

                var resultContent = result?.Result;

                if (resultContent == "重试")
                {
                    ReTryCheckSN(ProductSN);
                }
                else if (resultContent == "作为NG品")
                {
                    WriteToUser("当前产品过站失败，作为NG品下料", Brushes.Yellow, false);
                    if (Funs.FunCommSelection.Cur.IsUseNGBox)
                    {
                        Task.Run(() => { SubProcess.SubprocessUnloadNGProduct.Cur.Run(); });
                        MessageBox.Show("请将NG品放入NG料盒！");
                    }
                }
            }
        }

        private void RetryDataUp()
        {
            if (MESHelper.Cur.DataUp(GetFinalStation().CurrentProduct, out string mesError) == false)
            {
                Task<string> result = null;

                App.Current.Dispatcher.Invoke(() =>
                {
                    var content = $"DataUp 上传数据失败！{mesError} ! 是否重试？";
                    StaticInitial.Motion.WriteErrToUser(content);
                    result = new View.WarningView(content,
                        "重试", "作为NG品").ShowDialog();
                });

                var resultContent = result?.Result;

                if (resultContent == "重试")
                {
                    RetryDataUp();
                }
                else if (resultContent == "作为NG品")
                {
                    WriteToUser("当前产品上传数据失败，作为NG品下料", Brushes.Yellow, false);
                    GetFinalStation().CurrentProduct.Result = ProductInfo.ResultNG;
                    GetFinalStation().CurrentProduct.FailedMsg = "DataUp 上传数据失败";

                    if (Funs.FunCommSelection.Cur.IsUseNGBox)
                    {
                        Task.Run(() => { SubProcess.SubprocessUnloadNGProduct.Cur.Run(); });
                        MessageBox.Show("请将NG品放入NG料盒！");
                    }
                }
            }
        }

        public string GetTestValueItems(ProductInfo product)
        {
            StringBuilder sb = new StringBuilder(1024);
            foreach (var item in product.GetAllTestItems())
            {
                string resultStr = String.Empty;
                if (item.result == ProductInfo.ResultNG
                      || item.result == "0" || item.result.ToLower() == "ng"
                          || item.result.ToLower() == "fail")
                {
                    resultStr = "NG";
                }
                else
                {
                    resultStr = "OK";
                }
                sb.Append($"{item.name}@{item.lowLimit}@{item.upLimit}@{item.value}@{resultStr}|");
            }
            if (product.GetAllTestItems().Count != 0)
            {
                sb = sb.Remove(sb.Length - 1, 1);
            }
            sb.Append(";");
            sb.Append($"TestImage=;");
            sb.Append($"ResultImage=;");
            sb.Append($"Enabled=1;");

            return sb.ToString();
        }

        /// <summary>
        /// 清除界面数据事件
        /// </summary>
        public event Action ClearUIAction;

        /// <summary>
        /// 上料提示
        /// </summary>
        public event Action<string, Brush> LoadMsgEventHandler;

        /// <summary>
        /// 工位x数据显示
        /// </summary>
        public event Action<int, List<UdpItemData>> Site_ShowAction;

        /// <summary>
        /// 工位站 底部显示
        /// </summary>
        public event Action<string> Site_BottomShowAction;

        /// <summary>
        /// 结果显示事件
        /// </summary>
        public event Action<string, Brush> result_show_EventHandler;

        /// <summary>
        /// 上传界面出站产品各工位测试时间
        /// </summary>
        public event Action<double, double, double> StationTestTimeEndEventHandler;

        public string SN = "";

        private bool IsExit = false;

        /// <summary>
        /// 是否扫码
        /// </summary>
        private bool IsUseScanCode => Funs.FunCommSelection.Cur.IsUseScanCode;

        /// <summary>
        /// 当前是否是清料模式
        /// </summary>
        public bool IsClearMode { get; set; }

        /// <summary>
        /// NG报警暂停
        /// </summary>
        public bool IsNGAlarm { get; set; }

        public override void Stop()
        {
            IsExit = true;
            base.Stop();
        }

        private bool Io_in_SafeCheck()
        {
            if (Funs.FunCommSelection.Cur.IsUseSafetyGrating)
            {
                //给安全光栅信号取反
                return !StaticIOHelper.In_Safe_Checked.In();
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        ///  显示出站的SN
        /// </summary>
        /// <param name="str"></param>
        public void Site_ButtomShow(string str)
        {
            Site_BottomShowAction?.Invoke(str);
        }

        /// <summary>
        /// 添加工位1的数据显示
        /// </summary>
        /// <param name="udpItemDatas"></param>
        public void AddSite_Data(int stationNum, List<UdpItemData> udpItemDatas)
        {
            Site_ShowAction?.Invoke(stationNum, udpItemDatas);
        }

        /// <summary>
        /// 清除界面数据
        /// </summary>
        public void Clear_UI()
        {
            ClearUIAction?.Invoke();
        }

        /// <summary>
        /// 产品装载信息
        /// </summary>
        /// <param name="str"></param>
        /// <param name="brush"></param>
        public void WriteLoadMsg(string str, Brush brush)
        {
            LoadMsgEventHandler?.Invoke(str, brush);
        }

        /// <summary>
        /// 显示测试结果
        /// </summary>
        /// <param name="str"></param>
        /// <param name="brush"></param>
        public void WriteResultInfo(string str, Brush brush)
        {
            result_show_EventHandler?.Invoke(str, brush);
        }

        private void InitStationInfo()
        {
            for (int i = 0; i < GlobalParams.WorkstationSum; i++)
            {
                Process_TestStationBase.testStaionList[i].LoadProduct(null);
            }
        }

        private bool ISTestOK = false;

        /// <summary>
        /// 转盘转动过程中
        /// </summary> 
        public bool IsRoatedIsRunning { get; set; }

        public static StationSelectFunsBase CurWorkMode => WorkModeManager.Cur.SelectWorkMode;

        protected override ProcessAutoRunArgs ImplementImplementRunAction()
        {
            IsExit = false;
            IsNGAlarm = false;

            //获取当前使用者id
            string id = Wpf_LoginWnd.LoginHelper.Cur.CurUserMsg.ID;

            ProcessAutoRunArgs processAutoRunArgs = new ProcessAutoRunArgs();

            CheckActionHelper checkAction = new CheckActionHelper();
            AixRegisterInfodll.IoCheck ioCheck_IsLoadStart = new AixRegisterInfodll.IoCheck(StaticIOHelper.CheckIn_Start);

            Ref_Step("判断模式");
            IsRoatedIsRunning = false;
            IsClearMode = false;
            //关闭双启动按钮灯
            StaticIOHelper.StartLightOff();
            IOScanHelper.IsLoadStart = false;
            StaticIOHelper.Fun_ProductLight_OFF();//关闭产品指示灯

            string TempSN = "";
            ProductInfo productInfo_Temp = null;

            Sleep(100);
            //站位信息初始化
            InitStationInfo();

            try
            {
                WriteLoadMsg("等待上料", Brushes.AliceBlue);
                while (true)
                {
                    if (!IsProcessRunning)
                    {
                        IsExit = false;
                        break;
                    }
                    WaitPause();
                    switch (Step)
                    {
                        #region 初始化操作
                        case "判断模式":
                            if (CurWorkMode.Mode == WorkMode.SocketSpotInspection)
                            {
                                SocketSpotInspection.Cur.Run();
                                Ref_Step("退出");
                            }
                            else
                            {
                                Ref_Step("电机移动到等待位");
                            }
                            break;

                        case "电机移动到等待位":

                            StaticIOHelper.PowerOn();

                            //各个工位的'气缸'和'轴'到达等待位,按顺序最上先上
                            Parallel.Invoke(
                                () => FirstTestStation.Cur.AxiOrCylinderToWaitPos(),
                                () => SecondTestStation.Cur.AxiOrCylinderToWaitPos(),
                                () => ThirdTestStation.Cur.AxiOrCylinderToWaitPos(),
                                () => FourTestStation.Cur.AxiOrCylinderToWaitPos(),
                                () => FifthTestStation.Cur.AxiOrCylinderToWaitPos(),
                                () => SixthTestStation.Cur.AxiOrCylinderToWaitPos(),
                                () => PipeController.Cur.AllWait()
                               );

                            Sleep(100);

                            Ref_Step("判断治具情况");
                            break;

                        //下一步是“判断启动按钮按下”
                        case "判断治具情况":
                            if (!Io_in_SafeCheck())
                            {
                                try
                                {
                                    //转盘移动至最近未被禁用的治具
                                    for (int i = 0; i < GlobalParams.WorkstationSum; i++)
                                    {
                                        string fieldName = $"IsUseSocket{(char)(65 + i)}";
                                        if (GlobalParams.GetFieldValue<bool>(Funs.FunSocketSettings.Cur, fieldName))
                                        {
                                            WriteToUser("当前位置" + (i + 1));
                                            if (!Aixs.Aix_Turn.Cur.Mov_xPos(RotatedMovNextHelper.FixtureRotateDir == RotateDir.AntiClockWise ? i == 0 ? i : GlobalParams.WorkstationSum - i: i))
                                            {
                                                WriteErrToUser("旋转轴运动后位置检测无效！");
                                            }
                                            break;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    WriteErrToUser(ex.Message);
                                    break;
                                }

                                //若为线体模式(不会用到，直接跳过去)
                                if (CurWorkMode.Mode == WorkMode.AutoLine)
                                {
                                    Ref_Step("等待启动信号");
                                }
                                else
                                {
                                    //若开启点检功能选项(不会用到，直接跳过去)
                                    if (FunCommSelection.Cur.IsUseSpotCheck)
                                    {
                                        Ref_Step("产品信息预处理");
                                    }
                                    else
                                    {
                                        Ref_Step("判断启动按钮按下");
                                    }
                                }
                            }
                            else
                            {
                                WriteErrToUser("安全光栅被触发！\nSafety light curtain triggered");
                            }
                            break;
                        #endregion

                        #region 单颗产品测试完成后步骤

                        #region 正常模式
                        case "判断当前治具":
                            if (RotatedMovNextHelper.IsOkPos)
                            {
                                if (!CurrentSocketCanUse)
                                {
                                    WriteToUser($"当前载具为{RotatedMovNextHelper.tagPos[0]},当前载具被屏蔽，自动转往下一工位", Brushes.Yellow, false);

                                    Ref_Step("检查治具是否锁紧");
                                    //Ref_Step("判断启动按钮按下");
                                    break;
                                }
                                else
                                {
                                    Ref_Step("判断启动按钮按下");
                                }
                            }
                            break;
                        #endregion

                        #region 点检模式 | 无用跳过

                        case "判断点检品是否注册":
                            if (SpotInspectionFacility.ProductInfoManger.Cur.CheckProductIsRegister())
                            {
                                Ref_Step("产品信息预处理");
                            }
                            else
                            {
                                WriteErrToUser("点检品未注册!\nInspection item not registered!");
                                break;
                            }
                            break;

                        #endregion 点检模式

                        #region 线体模式 | 无用

                        case "等待启动信号":
                            //线体模式
                            Ref_Step("判断NG产品");
                            break;

                        #endregion 线体模式

                        #endregion

                        #region 启动运行时
                        case "判断启动按钮按下":
                            StaticIOHelper.StartLightOn();

                            if (IOScanHelper.IsLoadStart)
                            {
                                WriteToUser($"检测到按下启动按钮", Brushes.Yellow, false);
                                IOScanHelper.IsLoadStart = false;
                                //关闭启动产品灯
                                StaticIOHelper.StartLightOff();
                                WriteResultInfo("Testing", Brushes.Yellow);

                                if (Funs.FunCommSelection.Cur.IsUseSpotCheck)
                                {
                                    Ref_Step("判断上料产品是否扫码完成");
                                    break;
                                }
                                else
                                {
                                    //一步到位
                                    Ref_Step("判断NG产品");
                                }
                            }
                            break;

                        //判断NG品是否下料完成
                        case "判断NG产品":
                            Sleep(1000);
                            //NG产品下料完成，ng下料流程显示通过，但没有ng料标志，IsWaitNGProductUnload为true时
                            if (SubProcess.SubprocessUnloadNGProduct.Cur.IsWaitNGProductUnload && !IsNGAlarm)
                            {
                                IsNGAlarm = true;
                                break;
                            }
                            else
                            {
                                if (IsNGAlarm)
                                {
                                    IsNGAlarm = false;
                                    //下面两条语句作用一样：当前程序不处于等待ng下料
                                    SubProcess.SubprocessUnloadNGProduct.Cur.IsWaitNGProductUnload = false;
                                    SubProcess.SubprocessUnloadNGProduct.Cur.Stop();
                                }

                                Ref_Step("判断上料产品是否扫码完成");
                            }
                            break;

                        case "判断上料产品是否扫码完成":
                            //判断是否扫码。不扫码的情况：扫码被禁用、清料模式、当前治具不可用
                            if (IsUseScanCode && !IsClearMode && CurrentSocketCanUse)
                            {
                                if (string.IsNullOrEmpty(SN))
                                {
                                    WriteErrToUser("请先扫码！\nPlease scan the code first");
                                    break;
                                }
                            }

                            Ref_Step("检查治具是否锁紧");
                            break;

                        case "检查治具是否锁紧":
                            //做治具开合检测，准备产品信息构成信息对象
                            //若治具没有关紧  转盘轴的SafeCheck方法确保不干涉其他部件
                            if (!StaticIOHelper.Fun_CheckSocketClosed())
                            {
                                WriteErrToUser("当前治具未锁紧!\nCarrier not properly secured");
                                break;
                            }

                            //关闭产品指示灯
                            StaticIOHelper.Fun_ProductLight_OFF();

                            //清除页面SN信息
                            Clear_UI();

                            Ref_Step("创建产品实例");
                            break;

                        case "创建产品实例":

                            ProductInfo productInfo = new ProductInfo();

                            //清料模式和上料位载具屏蔽情况下产品为空
                            if (IsClearMode || !CurrentSocketCanUse)
                            {
                                productInfo = null;
                            }
                            else
                            {
                                //之所以不使用扫码，是因为扫码枪不能用把？
                                if (!IsUseScanCode)
                                {
                                    TempSN = DateTime.Now.ToString("yyyyMMddHHmmss") + "_DisableScanner";
                                }
                                else
                                {
                                    TempSN = SN;
                                }

                                SN = "";

                                //记录当前产品SN码
                                productInfo.Number = TempSN;
                                //记录当前产品的治具号
                                productInfo.PARA = RotatedMovNextHelper.tagPos[0];
                                //获取治具SN
                                productInfo.Socket = SocketSNSetting.Cur.GetSocketSN(productInfo.PARA);
                                productInfo.StartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            }

                            productInfo_Temp = productInfo;

                            Ref_Step("判断当前治具探针状态");

                            IsRoatedIsRunning = true;
                            break;

                        case "判断当前治具探针状态":
                            //获取上料位治具号并判断该治具是否可用
                            string CurFixtureOfFirstStation = RotatedMovNextHelper.tagPos[0];
                            if (!OtherParamHelper.Cur.CheckXProbe(CurFixtureOfFirstStation))
                            {
                                WriteErrToUser($"当前治具探针使用次数已达极限，请联系工程师进行更换！\nThe probe usage count for Fixture {CurFixtureOfFirstStation} at the current loadingposition has reached its maximum limit. Please contact engineering personnel to replace the probe andreset the usage count before continuing to use the equipment");
                                break;
                            }
                            MachineLifeVariableManger.Current.AddCountOnce(OtherParamHelper.TYPE_COMPONENT_PROBE, $"{CurFixtureOfFirstStation}治具探针");

                            Ref_Step("产品装载完成,转盘转动");

                            break;

                        case "产品装载完成,转盘转动":
                            //治具开合检测通过，安全光栅正常未被触发（安全系统接常闭，线路有问题也便于预防）
                            if (StaticIOHelper.Fun_CheckSocketClosed() && StaticIOHelper.In_Safe_Checked.In())
                            {
                                try
                                {
                                    //旋转轴转动到下一工位
                                    if (Aixs.RotatedMovNextHelper.MovNext())
                                    {
                                        WriteResultInfo("", Brushes.AliceBlue);
                                        ReportMsg("主轴位置：" + Aixs.Aix_Turn.Cur.GetEncPos().ToString("F3"));
                                        ReportMsg("位置比较结果：" + (Math.Abs(Aixs.Aix_Turn.Cur.GetEncPos() - Aixs.Aix_Turn.Cur.WaitPos.PosMsg.GetValue) % Aixs.Aix_Turn.PerRad).ToString());
                                        IOScanHelper.IsLoadStart = false;
                                        Ref_Step("产品信息预处理");
                                    }
                                    else
                                    {
                                        WriteErrToUser("旋转轴运动后位置检测无效！");
                                        break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    WriteErrToUser(ex.Message);
                                    break;
                                }
                            }
                            else
                            {
                                if (!StaticIOHelper.Fun_CheckSocketClosed())
                                {
                                    WriteErrToUser("当前治具未锁紧！\nAbnormality detected in the opening and closing of the carrier: The carrier is not properly fastened");
                                }
                                else
                                {
                                    WriteErrToUser("安全光栅被触发!\nThe safety light curtain is triggered");
                                }
                            }
                            break;

                        case "产品信息预处理":
                            //清料模式意味着不用扫码也可以将转盘移动至下一位置
                            if (IsClearMode)
                            {
                                WriteLoadMsg("清料模式中", Brushes.AliceBlue);

                                //若是n个工位，需要保证从1到n-1个工位都没有产品信息
                                if (HasClearingModeFinished())
                                {
                                    WriteToUser("=======================================================");
                                    WriteToUser("清料完成!");
                                    MessageBox.Show("清料完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
                                }
                            }
                            else
                            {
                                WriteLoadMsg("等待上料", Brushes.AliceBlue);
                            }

                            //判断产品，最后一个工站都有数据了，意味着该下料了，故处理下料信息
                            if (GetFinalStation().CurrentProduct != null)
                            {
                                GetFinalStation().CurrentProduct.EndTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                //下料产品检测ok
                                if (GetFinalStation().CurrentProduct.Result == ProductInfo.ResultOK)
                                {
                                    ISTestOK = true;
                                    ProductNumberManager.Cur.OKNums++;

                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        AddRateStatistic(AviewMotionUI.ProductionStatistics.ProductResult.OK);
                                    });

                                    WriteResultInfo("Pass", Brushes.Green);
                                    StaticIOHelper.Fun_ProductLightGreen();
                                }
                                //下料产品检测ng
                                else
                                {
                                    WriteResultInfo("Fail", Brushes.Red);
                                    StaticIOHelper.Fun_ProductLightRed();

                                    ISTestOK = false;
                                    ProductNumberManager.Cur.NgNums++;
                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        AddRateStatistic(AviewMotionUI.ProductionStatistics.ProductResult.NG);
                                    });

                                    //添加工站ng计数
                                    try
                                    {
                                        AddTestStationNGCount();
                                    }
                                    catch (Exception e)
                                    {
                                        WriteToUser("ng计数统计执行出现异常！" + e.Message);
                                    }

                                    //根据条件执行ng下料流程
                                    if (FunCommSelection.Cur.IsUseNGBox)
                                    {
                                        Task.Run(() => { SubProcess.SubprocessUnloadNGProduct.Cur.Run(); });
                                    }
                                }

                                flushTestResult();

                                string temp = $"SN={GetFinalStation().CurrentProduct.Number};PARA={GetFinalStation().CurrentProduct.PARA};Socket={GetFinalStation().CurrentProduct.Socket}";
                                //展示下料产品SN
                                Site_ButtomShow(temp);
                            }

                            Ref_Step("打印机开始工作");

                            break;

                        case "打印机开始工作":
                            if (Funs.FunCommSelection.Cur.IsUsePrint)
                            {
                                WriteToUser($"当前设备总数为:" + ProductionStatisticsManger.Current.TotalYieldArray.YieldPercent.TotalCount.ToString(), Brushes.Yellow, false);
                                if (ZebraHelper.SendZebra(GetFinalStation().CurrentProduct.Number, ProductionStatisticsManger.Current.TotalYieldArray.YieldPercent.TotalCount, GetFinalStation().CurrentProduct.Result))
                                {
                                    WriteToUser("打印完成");
                                }
                                else
                                {
                                    WriteErrToUser("数据获取错误，请人工检查文件");
                                }
                            }
                            else
                            {
                                WriteToUser("打印机被禁用，跳过此步骤！");
                            }

                            Ref_Step("MES上传数据");

                            break;

                        case "MES上传数据":
                            if (Funs.FunCommSelection.Cur.IsUseMes)
                            {
                                if (GetFinalStation().CurrentProduct != null && !FunCommSelection.Cur.IsUseSpotCheck)
                                {
                                    RetryDataUp();
                                }
                            }
                            else
                            {
                                WriteToUser("Mes被禁用，跳过此步骤！");
                            }

                            Ref_Step("写Log");
                            break;

                        case "写Log":
                            if (GetFinalStation().CurrentProduct != null)
                            {
                                var timeNow = DateTime.Now;
                                CsvHelper csvTest = new CsvHelper(() => $"..//data//{timeNow.ToString("yyyy")}//{timeNow.ToString("yyyy-MM-dd")}//{WorkItemManagerHelper.LoadedName}", () => "FinalTest.csv");

                                csvTest.SetCSVHeader("SN", "Programver", "Model", "StartTime", "EndTime", "MachineName", "Operator", "Result", "TestItems" + "\r\n",
                                                      "产品序列号", "程序版本号", "产品型号", "开始时间", "结束时间", "设备名称", "操作人员", "结果", "测试项及结果" + "\r\n",
                                                      "製品シリアル番号", "プログラムバージョン番号", "製品型番", "開始時間", "終了時間", "デバイス名", "オペレータ", "結果＃ケッカ＃", "試験項目及び結果" + "\r\n",
                                                      "-", "-", "-", "-", "-", "-", "-", "-", "-" + "\r\n", "-", "-", "-", "-", "-", "-", "-", "-", "-");

                                var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                                var startTime = GetFinalStation().CurrentProduct.StartTime;
                                var endTime = GetFinalStation().CurrentProduct.EndTime;
                                string Operator = Wpf_LoginWnd.LoginHelper.Cur.CurUserMsg.Category.ToString() + " | " + Wpf_LoginWnd.LoginHelper.Cur.CurUserMsg.ID;

                                csvTest.WriteLine(GetFinalStation().CurrentProduct.Number, version, View.WorkItemManagerHelper.LoadedName, startTime, endTime, "FinalTestMachine", Operator, GetFinalStation().CurrentProduct.Result, GetTestValueItems(GetFinalStation().CurrentProduct));
                            }
                            else
                            {
                                WriteToUser("当前产品信息为空，跳过！");
                            }

                            Ref_Step("开始通知各工位测试");
                            break;

                        case "开始通知各工位测试":
                            //装载产品信息，把前一站信息装载到后一站里面
                            LoadAllStationInfo(productInfo_Temp);

                            IsRoatedIsRunning = false;

                            Parallel.Invoke(
                                () => SecondTestStation.Cur.Run(),
                                () => ThirdTestStation.Cur.Run(),
                                () => FourTestStation.Cur.Run(),
                                () => FifthTestStation.Cur.Run(),
                                () => SixthTestStation.Cur.Run()
                            );

                            StaticIOHelper.PowerOff();

                            Ref_Step("各工位测试完成");
                            break;

                        case "各工位测试完成":
                            WriteToUser($"Current working mode:{CurWorkMode.Mode}");

                            switch (CurWorkMode.Mode)
                            {
                                case WorkMode.Normal:
                                    Ref_Step("判断当前治具");
                                    break;

                                case WorkMode.AutoLine:
                                    Ref_Step("等待启动信号");
                                    break;

                                case WorkMode.SpotInspection:
                                    Ref_Step("产品信息预处理");
                                    break;

                                case WorkMode.TestRun:
                                    Ref_Step("检查治具是否锁紧");
                                    break;
                            }
                            break;
                        #endregion

                        case "退出":
                            IsProcessRunning = false;
                            processAutoRunArgs.IsExitOK = true;
                            IsRoatedIsRunning = false;
                            break;
                    }
                    Sleep(10);
                }
                processAutoRunArgs.IsExitOK = true;
                Motion.CommitStopOrder();
            }
            catch (Exception ex)
            {
                IsProcessRunning = false;
                IsRoatedIsRunning = false;
                WriteLoadMsg("", Brushes.AliceBlue);
                processAutoRunArgs.IsExitOK = false;
                processAutoRunArgs.ErrInfo = ex.Message;
                WriteErrToUser(ExceptionHelper.GetInnerExceptionMessageAndStackTrace(ex));
                Motion.CommitStopOrder();
            }
            finally
            {
                IsProcessRunning = false;
                IsRoatedIsRunning = false;
                WriteLoadMsg("", Brushes.AliceBlue);
            }

            return processAutoRunArgs;
        }

        private void AddTestStationNGCount()
        {
            for (int i = 1; i <= GlobalParams.WorkstationSum; i++)
            {
                string fieldName = "";
                if (GetFinalStation().CurrentProduct.GetTestStation(i).Result == TestResult.NG)
                {
                    fieldName = $"Site{i + 1}NG";
                    GlobalParams.SetPropertyValue(ProductNumberManager.Cur, fieldName, GlobalParams.GetPropertyValue<int>(ProductNumberManager.Cur, fieldName) + 1);
                }
            }
        }

        private void flushTestResult()
        {
            //将测试信息展示在主页面表格中
            for (int i = 1; i <= GlobalParams.WorkstationSum; i++)
            {
                AddSite_Data(i, UdpItemData.GetUdpItemsFromProductTestStationTestItem(GetFinalStation().CurrentProduct.GetTestStation(i).StationTestItems));
            }
        }

        private void AddRateStatistic(AviewMotionUI.ProductionStatistics.ProductResult result)
        {
            ProductionStatisticsManger.Current.AddCountOnce(result, GetFinalStation().CurrentProduct.PARA, Product.ProductConverter.GetProductStationResultItems(GetFinalStation().CurrentProduct).ToArray());
        }

        private void LoadAllStationInfo(ProductInfo productInfo_Temp)
        {
            for (int i = GlobalParams.WorkstationSum - 1; i > 1; i--)
            {
                Process_TestStationBase.testStaionList[i].LoadProduct(Process_TestStationBase.testStaionList[i - 1].CurrentProduct);
            }
            Process_TestStationBase.testStaionList[1].LoadProduct(productInfo_Temp);
        }

        private Process_TestStationBase GetFinalStation()
        {
            /*for (int i = GlobalParams.WorkstationSum; i > 1; i--) {
                if (GlobalParams.GetFieldValue<bool>(FunStationSettings.Cur, $"Site{i}IsUse"))
                {
                    return Process_TestStationBase.testStaionList[i-1];
                }
            }
            throw new Exception("当前所有测试工位都被禁用");*/
            return Process_TestStationBase.testStaionList[GlobalParams.WorkstationSum-1];
        }

        private bool HasClearingModeFinished()
        {
            foreach (var item in Process_TestStationBase.testStaionList)
            {
                if (item.CurrentProduct != null) return false;
            }
            return true;
        }
    }
}